import Vue from "vue";
import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css"; // 进度条样式
import getPageTitle from "@/utils/get-page-title";
import { getRefreshToken, parseToken } from "@/utils/token";
import { testTokenState } from "@/utils/tokenState";

NProgress.configure({ showSpinner: false }); // NProgress配置

const whiteList = [
  "/",
  "/work",
  "/searchwork",
  "/login",
  "/register",
  "/register_captcha",
  "/forget_password",
  "/forget_password_captcha"
]; // 重定向白名单

router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();

  // 设置页面标题
  document.title = getPageTitle(to.meta.title);
  let bearerToken = localStorage.getItem("bearerToken") || "";
  // testTokenState 查看token是否过期
  testTokenState();
  let tokenState = store.getters.tokenState;
  if (bearerToken && tokenState === "notExpired") {
    //未过期
    const hasRoles = store.getters.authority;
    if (hasRoles) {
      //TODO 判断用户权限和后台路由
      
      next();
    } else {
      try {
        // 获取用户信息,若获取不到，在getInfo方法内提示用户重新登录
        await store.dispatch("user/get_info");
        next();
      } catch (error) {
        // 删除令牌并转到登录页面重新登录
        let refreshToken = localStorage.getItem("refreshToken") || "";
        // 尝试刷新 token
        //getRefreshToken 方法刷新token
        if (refreshToken.length !== 0) {
          let refreshToken = await getRefreshToken();
          localStorage.setItem("refreshToken", refreshToken);
          next();
        } else {
          Vue.prototype.$message.error(error || "Has Error");
          //重定向到登录页面
          next(`/login?redirect=${to.path}`);
        }
        setTimeout(() => {
          NProgress.done();
        }, 300);
      }
    }
  } else {
    /*没有令牌*/

    if (whiteList.indexOf(to.path) !== -1) {
      //在免登录白名单中，直接进入
      next();
    } else {
      //其他没有权限访问的页面重定向到登录页面。
      next(`/login?redirect=${to.path}`);
      setTimeout(() => {
        NProgress.done();
      }, 300);
    }
  }
});

router.afterEach(() => {
  //完成进度条
  setTimeout(() => {
    NProgress.done();
  }, 300);
});
